
package com.xebest.web.service.impl;

import com.xebest.common.util.XeBaseUtil;
import com.xebest.web.form.XeVenCarForm;
import com.xebest.web.form.XeVenCarSendForm;
import com.xebest.web.form.XeVenOrderLogisticsForm;
import com.xebest.web.mapper.read.XeLogisticsCarReadMapper;
import com.xebest.web.mapper.read.XeVenOrderLogisticsReadMapper;
import com.xebest.web.mapper.write.XeVenOrderLogisticsWriteMapper;
import com.xebest.web.model.*;
import com.xebest.web.service.XeVenOrderLogisticsService;
import com.xebest.web.view.XeVenOrderLogisticsView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class XeVenOrderLogisticsServiceImpl implements XeVenOrderLogisticsService {

	@Autowired
	private XeVenOrderLogisticsReadMapper logisticsReadMapper;// 读取物流信息

	@Autowired
	private XeVenOrderLogisticsWriteMapper logisticsWriteMapper;// 写物流信息
	@Autowired
	private XeLogisticsCarReadMapper xeLogisticsCarReadMapper;// 写物流车辆信息

	// 获取物流信息
	@Override
	public List<XeVenOrderLogistics> selectLogisticsList(XeVenOrderLogisticsForm logisticsForm) {

		return logisticsReadMapper.selectLogisticsList(logisticsForm);
	}

	// 获取物流详情
	@Override
	public List<XeVenOrderLogisticsDetail> selectLogisticsDetailList(XeVenOrderLogisticsForm logisticsForm) {

		return logisticsReadMapper.selectLogisticsDetailList(logisticsForm);
	}

	// 根据物流单号删除物流信息
	@Override
	@Transactional(value = "writeTransactionManager")
	public int deleteLogisticsByLogtsCode(String logtsCode) {

		return logisticsWriteMapper.deleteLogisticsByLogtsCode(logtsCode);
	}

	// 添加物流信息
	@Override
	@Transactional(value = "writeTransactionManager")
	public int insertLogistics(XeVenOrderLogistics xeVenOrderLogistics) {

		return logisticsWriteMapper.insertLogistics(xeVenOrderLogistics);
	}

	// 修改物流信息
	@Override
	@Transactional(value = "writeTransactionManager")
	public int updateLogisticsByLogtsCode(XeVenOrderLogistics xeVenOrderLogistics) {

		return logisticsWriteMapper.updateLogisticsByLogtsCode(xeVenOrderLogistics);
	}

	// 添加物流明细
	@Override
	@Transactional(value = "writeTransactionManager")
	public int insertLogisticsDetail(XeVenOrderLogisticsDetail logisticsDetail) {

		return logisticsWriteMapper.insertLogisticsDetail(logisticsDetail);
	}

	// 修改物流明细
	@Override
	@Transactional(value = "writeTransactionManager")
	public int updateLogisticsDetailLogtsCode(XeVenOrderLogisticsDetail logisticsDetail) {

		return logisticsWriteMapper.updateLogisticsDetailLogtsCode(logisticsDetail);
	}

	/*
	 * 根据订单号查询物流详情 (non-Javadoc)
	 * 
	 * @see
	 * com.xebest.web.service.XeVenOrderLogisticsService#listLogisticsDetail(
	 * java.lang.String,java.lang.String)
	 */

	@Override
	public List<XeVenOrderLogisticsDetail> listLogisticsDetail(String orderId, String createDateStr) {

		return logisticsReadMapper.listLogisticsDetail(orderId, createDateStr);
	}

	/*
	 * 获取最新的一条物流信息 (non-Javadoc)
	 * 
	 * @see
	 * com.xebest.web.service.XeVenOrderLogisticsService#getLatestLogistics(java
	 * .lang.String)
	 */
	@Override
	public XeVenOrderLogisticsDetail getLatestLogistics(String userId) {

		return logisticsReadMapper.getLatestLogistics(userId);

	}

	/**
	 * 物流单查询列表
	 */
	@Override
	public List<XeVenOrderLogisticsView> queryOrderLogisticsList(XeVenOrderLogisticsForm form) {

		List<XeVenOrderLogisticsView> logisticsViews = logisticsReadMapper.queryOrderLogisticsList(form);
		for (XeVenOrderLogisticsView logisticsView : logisticsViews) {
			if (!StringUtils.isEmpty(logisticsView.getCaAreaId())) {
				String area = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(logisticsView.getCaAreaId()));
				logisticsView.setReceiptArea(area + "-" + logisticsView.getCaStreet());
			}
		}
		return logisticsViews;

	}

	/**
	 * 物流单查询，客户信息
	 */
	@Override
	public Map<String, Object> queryCustomerLogisticsDetail(XeVenOrderLogisticsForm form) {
		Map<String, Object> cus = logisticsReadMapper.queryCustomerLogisticsDetail(form);
		if (null != cus) {
			if (!StringUtils.isEmpty(cus.get("caAreaId"))) {
				String area = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(cus.get("caAreaId").toString()));
				cus.put("receiptAddress", area + cus.get("caStreet"));
			}
		}
		return cus;

	}

	/**
	 * 物流单查询备注信息
	 */
	@Override
	public Map<String, Object> queryRemarkLogisticsDetail(XeVenOrderLogisticsForm form) {

		return logisticsReadMapper.queryRemarkLogisticsDetail(form);

	}

	/**
	 * 根据物流单号查询派车页所需信息
	 */
	@Override
	public Map<String, Object> querySendCarLogisticsByLogtsCode(XeVenOrderLogisticsForm form) {
		Map<String, Object> lMap = logisticsReadMapper.querySendCarLogisticsByLogtsCode(form);
		if (null != lMap) {
			if (!StringUtils.isEmpty(lMap.get("caAreaId"))) {
				String area = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(lMap.get("caAreaId").toString()));
				lMap.put("receiptAddress", area + lMap.get("caStreet"));
			}
		}
		return lMap;
	}

	/**
	 * 根据区域，用户,获取已派车物流单的车辆信息
	 */
	@Override
	public Map<String, Object> querylatelySendCarLogistics(Map<String, Object> paraMap) {

		return logisticsReadMapper.querylatelySendCarLogistics(paraMap);

	}

	/**
	 * 查询车辆列表
	 */
	@Override
	public List<Map<String, Object>> queryCarList(XeVenOrderLogisticsForm form) {

		List<Map<String, Object>> carList = logisticsReadMapper.queryCarList(form);
		for (Map<String, Object> car : carList) {
			StringBuffer routeStr = new StringBuffer("");
			String starAreas = car.get("startAreaIds") + "";
			String endAreas = car.get("endAreaIds") + "";
			car.put("address", "");
			if (!StringUtils.isEmpty(starAreas) && !StringUtils.isEmpty(endAreas)) {
				String[] starAreaArr = starAreas.split("_");
				String[] endAreaArr = endAreas.split("_");
				for (int i = 0; i < starAreaArr.length; i++) {
					String starArea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(starAreaArr[i]));
					String endArea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(endAreaArr[i]));
					routeStr.append(starArea);
					routeStr.append("——");
					routeStr.append(endArea);
					routeStr.append("；");
				}
				car.put("address", routeStr);
			}
		}
		return carList;

	}

	/**
	 * 保存车辆信息
	 */
	@Override
	@Transactional(value = "writeTransactionManager")
	public int saveCarInfo(XeVenCarForm form) {
		int result = 0;
		XeVenCarEntity carEntity = new XeVenCarEntity();
        Integer maxCarId = xeLogisticsCarReadMapper.getMaxCarId();
        maxCarId = maxCarId == null ? 1 : maxCarId;
		//carEntity.setCarId(Integer.parseInt(FinanceSeqUtil.seqUtils.getNextSeq(XeVenSeqContents.ERP_VEN_CARID_CODE, "10")));
		carEntity.setCarId(maxCarId+1);
		carEntity.setUserCode(form.getUserCode());
		carEntity.setCarPlateNum(form.getCarPlateNum());
		carEntity.setCarSource(1);
		carEntity.setCarLength(form.getCarLength());
		carEntity.setContactPerson(form.getContactPerson());
		carEntity.setMobilePhone(form.getMobilePhone());
		form.setCarId(carEntity.getCarId());
		// 保存车辆信息
		result = logisticsWriteMapper.saveCarInfo(carEntity);
		XeVenCarLinesEntity carLinesEntity = new XeVenCarLinesEntity();
		carLinesEntity.setCarId(form.getCarId());
		carLinesEntity.setCreateUser(form.getCreateUser());
		carLinesEntity.setStartProvinceId(form.getProvinceId());
		carLinesEntity.setStartCityId(form.getCityId());
		carLinesEntity.setStartAreaId(form.getAreaId());
		carLinesEntity.setEndProvinceId(form.getCaProvinceId());
		carLinesEntity.setEndCityId(form.getCaCityId());
		carLinesEntity.setEndAreaId(form.getCaAreaId());
		// 保存承运路线信息
		result = logisticsWriteMapper.saveCarLines(carLinesEntity);
		XeVenCarUsesRecordEntity carUsesRecordEntity = new XeVenCarUsesRecordEntity();
		carUsesRecordEntity.setCarId(form.getCarId());
		carUsesRecordEntity.setUserCode(form.getUserCode());
		// 保存使用过的车辆信息
		Map<String, Object> carUsesRecord = logisticsWriteMapper.selectCarUsesRecordByLogtCode(carUsesRecordEntity);
		if (null == carUsesRecord) {
			// 新增
			result = logisticsWriteMapper.saveCarUsesRecord(carUsesRecordEntity);
		}
		return result;

	}

	/**
	 * 保存派车信息
	 */
	@Override
	@Transactional(value = "writeTransactionManager")
	public int saveSendCarInfo(XeVenCarSendForm form) {

		XeVenCarSendEntity carSendEntity = new XeVenCarSendEntity();
		carSendEntity.setModifyDate(new Date());
		carSendEntity.setModifyUser(form.getCreateUser());
		BeanUtils.copyProperties(form, carSendEntity);
		int rs = 0;
		Map<String, Object> sendCarMap = logisticsWriteMapper.selectSendCarInfoByLogtCode(form.getLogtCode());
		if (null != sendCarMap && sendCarMap.size() > 0) {
			// 更新
			rs = logisticsWriteMapper.updateSendCarInfo(carSendEntity);
		} else {
			// 新增
			rs = logisticsWriteMapper.saveSendCarInfo(carSendEntity);
		}
		XeVenCarUsesRecordEntity carUsesRecordEntity = new XeVenCarUsesRecordEntity();
		carUsesRecordEntity.setCarId(form.getCarId());
		carUsesRecordEntity.setUserCode(form.getUserCode());

		Map<String, Object> carUsesRecordMap = logisticsWriteMapper.selectCarUsesRecordByLogtCode(carUsesRecordEntity);
		if (null == carUsesRecordMap) {
			// 新增
			rs = logisticsWriteMapper.saveCarUsesRecord(carUsesRecordEntity);
		}

		if (form.getUpFlag() == 1) {
			// 修改派车时,修改物流描述信息
			XeVenOrderLogisticsDetail orderLogisticsDetail = new XeVenOrderLogisticsDetail();
			orderLogisticsDetail.setUserCode(form.getUserCode());
			orderLogisticsDetail.setLogtsCode(form.getLogtCode());
			orderLogisticsDetail.setLogtsStatus(7);
			orderLogisticsDetail.setLogtsDesc("您的包裹已安排承运车辆：" + form.getCarPlateNum() + "，"
					+ (StringUtils.isEmpty(form.getContactPerson()) == true ? "".toString()
							: form.getContactPerson() + "，")
					+ form.getMobilePhone() + "。" + "预计" + form.getLoadTime() + "装车，装车点：" + form.getLoadAddr());
			rs = updateLogisticsDetailLogtsCode(orderLogisticsDetail);
			logisticsWriteMapper.updateReceiptStatusByLogtsCode(form.getLogtCode());
		} else {
			// 更新物流单派车状态
			XeVenOrderLogistics orderLogistics = new XeVenOrderLogistics();
			orderLogistics.setLogtsCode(form.getLogtCode());
			orderLogistics.setCarSendStatus(2);
			orderLogistics.setUserCode(form.getUserCode());
			orderLogistics.setLogtsNumber(form.getExpressNumber());
			orderLogistics.setLogtsCompany(form.getExpressName());
			rs = logisticsWriteMapper.updateLogisticsByLogtsCode(orderLogistics);
			// 添加物流信息明细
			XeVenOrderLogisticsDetail orderLogisticsDetail = new XeVenOrderLogisticsDetail();
			orderLogisticsDetail.setCreateUser(form.getCreateUser());
			orderLogisticsDetail.setUserCode(form.getUserCode());
			orderLogisticsDetail.setLogtsCode(form.getLogtCode());
			orderLogisticsDetail.setLogtsStatus(7);
			orderLogisticsDetail.setLogtsDesc("您的包裹已安排承运车辆：" + form.getCarPlateNum() + "，"
					+ (StringUtils.isEmpty(form.getContactPerson()) == true ? "".toString()
							: form.getContactPerson() + "，")
					+ form.getMobilePhone() + "。" + "预计" + form.getLoadTime() + "装车，装车点：" + form.getLoadAddr());
			rs = insertLogisticsDetail(orderLogisticsDetail);
		}
		return rs;

	}

	@Override
	public Map<String, Object> queryOrderStateByLogtCode(String logtCode) {

		return logisticsReadMapper.queryOrderStateByLogtCode(logtCode);

	}

	@Override
	public Map<String, Object> queryCarLinesByCarId(Integer carId) {

		return logisticsReadMapper.queryCarLinesByCarId(carId);

	}

	/**
	 * 保存车辆承运线路
	 */
	@Override
	@Transactional(value = "writeTransactionManager")
	public int saveCarLines(XeVenCarSendForm form) {

		XeVenCarLinesEntity carLinesEntity = new XeVenCarLinesEntity();
		carLinesEntity.setCarId(form.getCarId());
		carLinesEntity.setCreateUser(form.getCreateUser());
		carLinesEntity.setStartProvinceId(form.getProvinceId());
		carLinesEntity.setStartCityId(form.getCityId());
		carLinesEntity.setStartAreaId(form.getAreaId());
		carLinesEntity.setEndProvinceId(form.getCaProvinceId());
		carLinesEntity.setEndCityId(form.getCaCityId());
		carLinesEntity.setEndAreaId(form.getCaAreaId());
		return logisticsWriteMapper.saveCarLines(carLinesEntity);

	}

	/**
	 * 根据物流单号数组查询派车页所需信息
	 */
	@Override
	public List<Map<String, Object>> querySendCarLogisticsByLogtsCodeArr(XeVenOrderLogisticsForm form) {
		List<Map<String, Object>> sendCarLogistics = logisticsReadMapper.querySendCarLogisticsByLogtsCodeArr(form);
		for (Map<String, Object> car : sendCarLogistics) {
			if (!StringUtils.isEmpty(car.get("caAreaId"))) {
				String area = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(car.get("caAreaId").toString()));
				car.put("receiptAddress", area + "-" + car.get("caStreet"));
			}
		}
		return sendCarLogistics;

	}

	/**
	 * 根据物流单号数组查询当前订单状态
	 */
	@Override
	public List<Map<String, Object>> queryOrderStateByLogtCodeArr(String[] logtCodeArr) {

		return logisticsReadMapper.queryOrderStateByLogtCodeArr(logtCodeArr);

	}

	/**
	 * 保存批量派车数据
	 */
	@Override
	@Transactional(value = "writeTransactionManager")
	public int saveBathSendCarInfo(XeVenCarSendForm form) {

		int rs = 0;
		rs = logisticsWriteMapper.deleteXeVenCarSendByLogtCode(form);
		List<XeVenCarSendEntity> carSendEntityList = new ArrayList<XeVenCarSendEntity>();
		for (int i = 0; i < form.getLogtCodeArr().length; i++) {
			XeVenCarSendEntity carSendEntity = new XeVenCarSendEntity();
			carSendEntity.setCarId(form.getCarId());
			carSendEntity.setLogtCode(form.getLogtCodeArr()[i]);
			carSendEntity.setUserCode(form.getUserCode());
			carSendEntity.setLoadAddr(form.getLoadAddr());
			carSendEntity.setLoadTime(form.getLoadTime());
			carSendEntity.setUnloadAddr(form.getUnloadAddr());
			carSendEntity.setUnloadTime(form.getUnloadTime());
			carSendEntity.setRemark(form.getRemark());
			carSendEntity.setCreateUser(form.getCreateUser());
			carSendEntityList.add(carSendEntity);
		}
		// 保存
		rs = logisticsWriteMapper.saveBathSendCarInfo(carSendEntityList);

		XeVenCarUsesRecordEntity carUsesRecordEntity = new XeVenCarUsesRecordEntity();
		carUsesRecordEntity.setCarId(form.getCarId());
		carUsesRecordEntity.setUserCode(form.getUserCode());
		Map<String, Object> carUsesRecord = logisticsWriteMapper.selectCarUsesRecordByLogtCode(carUsesRecordEntity);
		if (null == carUsesRecord) {
			// 新增
			rs = logisticsWriteMapper.saveCarUsesRecord(carUsesRecordEntity);
		}

		// 修改物流单派车状态
		XeVenOrderLogistics orderLogistics = new XeVenOrderLogistics();
		orderLogistics.setLogtsCodeArr(form.getLogtCodeArr());
		orderLogistics.setCarSendStatus(2);
		orderLogistics.setUserCode(form.getUserCode());
		rs = logisticsWriteMapper.updateBathLogisticsByLogtsCode(orderLogistics);
		// 查询物流明细是否存在
		XeVenOrderLogisticsForm logisticsForm = new XeVenOrderLogisticsForm();
		logisticsForm.setLogtsCodeArr(form.getLogtCodeArr());
		logisticsForm.setLogtsStatus(7);
		logisticsForm.setUserCode(form.getUserCode());
		Long logisDetailNumber = logisticsReadMapper.selectLogisticsDetailListNumber(logisticsForm);
		// 有派车明细更新
		if (logisDetailNumber > 0) {
			// 修改派车时,修改物流描述信息
			// 删除物流明细信息
			rs = logisticsWriteMapper.deleteBathLogisticsDetailLogtsCode(form);
			// 添加物流信息明细
			List<XeVenOrderLogisticsDetail> orderLogisticsDetailList = new ArrayList<XeVenOrderLogisticsDetail>();
			for (int j = 0; j < form.getLogtCodeArr().length; j++) {
				XeVenOrderLogisticsDetail orderLogisticsDetailInsert = new XeVenOrderLogisticsDetail();
				orderLogisticsDetailInsert.setCreateUser(form.getCreateUser());
				orderLogisticsDetailInsert.setUserCode(form.getUserCode());
				orderLogisticsDetailInsert.setLogtsCode(form.getLogtCodeArr()[j]);
				orderLogisticsDetailInsert.setLogtsStatus(7);
				orderLogisticsDetailInsert.setLogtsDesc("您的包裹已安排承运车辆：" + form.getCarPlateNum() + "，"
						+ (StringUtils.isEmpty(form.getContactPerson()) == true ? "".toString()
								: form.getContactPerson() + "，")
						+ form.getMobilePhone() + "。" + "预计" + form.getLoadTime() + "装车，装车点：" + form.getLoadAddr());
				orderLogisticsDetailList.add(orderLogisticsDetailInsert);
			}
			rs = logisticsWriteMapper.insertBathLogisticsDetail(orderLogisticsDetailList);
		} else {// 没有派车明细新增
				// 添加物流信息明细
			List<XeVenOrderLogisticsDetail> orderLogisticsDetailList = new ArrayList<XeVenOrderLogisticsDetail>();
			for (int j = 0; j < form.getLogtCodeArr().length; j++) {
				XeVenOrderLogisticsDetail orderLogisticsDetailInsert = new XeVenOrderLogisticsDetail();
				orderLogisticsDetailInsert.setCreateUser(form.getCreateUser());
				orderLogisticsDetailInsert.setUserCode(form.getUserCode());
				orderLogisticsDetailInsert.setLogtsCode(form.getLogtCodeArr()[j]);
				orderLogisticsDetailInsert.setLogtsStatus(7);
				orderLogisticsDetailInsert.setLogtsDesc("您的包裹已安排承运车辆：" + form.getCarPlateNum() + "，"
						+ (StringUtils.isEmpty(form.getContactPerson()) == true ? "".toString()
								: form.getContactPerson() + "，")
						+ form.getMobilePhone() + "。" + "预计" + form.getLoadTime() + "装车，装车点：" + form.getLoadAddr());
				orderLogisticsDetailList.add(orderLogisticsDetailInsert);
			}
			rs = logisticsWriteMapper.insertBathLogisticsDetail(orderLogisticsDetailList);
		}
		return rs;
	}

	@Override
	public List<XeVenOrderLogisticsView> querySendCarList(XeVenOrderLogisticsForm form) {
		List<XeVenOrderLogisticsView> loList = logisticsReadMapper.querySendCarList(form);
		for (XeVenOrderLogisticsView logisticsView : loList) {
			if (!StringUtils.isEmpty(logisticsView.getAreaId()) && !StringUtils.isEmpty(logisticsView.getCaAreaId())) {
				String area = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(logisticsView.getAreaId()));
				logisticsView.setStoreArea(area);
				String rearea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(logisticsView.getCaAreaId()));
				logisticsView.setReceiptArea(rearea + "-" + logisticsView.getCaStreet());
			}
		}
		return loList;

	}

	@Override
	public List<Map<String, Object>> queryAllCarList(XeVenOrderLogisticsForm form) {
		List<Map<String, Object>> carList = logisticsReadMapper.queryAllCarList(form);
		for (Map<String, Object> car : carList) {
			StringBuffer routeStr = new StringBuffer("");
			String starAreas = car.get("startAreaIds") + "";
			String endAreas = car.get("endAreaIds") + "";
			car.put("address", "");
			if (!StringUtils.isEmpty(starAreas) && !StringUtils.isEmpty(endAreas)) {
				String[] starAreaArr = starAreas.split("_");
				String[] endAreaArr = endAreas.split("_");
				for (int i = 0; i < starAreaArr.length; i++) {
					String starArea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(starAreaArr[i]));
					String endArea = XeBaseUtil.baseUtil.getOrgAreaName(Integer.parseInt(endAreaArr[i]));
					routeStr.append(starArea);
					routeStr.append("——");
					routeStr.append(endArea);
					routeStr.append("；");
				}
				car.put("address", routeStr);
			}
		}
		return carList;

	}

	/**
	 * 获取装车点，卸货点默认值，及历史记录
	 * 
	 * @author: 赵盼飞
	 * @createTime: 2017年10月19日 下午5:36:55
	 * @history:
	 * @param carForm
	 * @return List<Map<String,Object>>
	 */
	@Override
	public List<Map<String, Object>> queryCarAddressList(XeVenCarForm carForm) {

		return logisticsReadMapper.queryCarAddressList(carForm);

	}

	/**
	 * 获取装车点，卸货点默认值，及历史记录 只获取最近一条
	 * 
	 * @author: 赵盼飞
	 * @createTime: 2017年10月19日 下午5:36:55
	 * @history:
	 * @param carForm
	 * @return List<Map<String,Object>>
	 */
	@Override
	public Map<String, Object> queryCarAddress(XeVenCarForm carForm) {

		return logisticsReadMapper.queryCarAddress(carForm);

	}

	/**
	 * 根据carId查询车辆信息
	 */
	@Override
	public Map<String, Object> queryCarInfoByCarId(Integer carId) {

		return logisticsReadMapper.queryCarInfoByCarId(carId);

	}

}
